var path = require('path');
var express = require('express');
const https = require('https');
const fs = require('fs');
const http = require('http');
const initSocket = require('./websocket/socket_io')
const yun = express();
const os = require('os');
const logjs = require('./config/logjs.js'); // 日志中间件
const routerReq = require('./config/router-req.js')
// 读取证书,__dirname获取当前文件所在目录__filename是获取文件路径
let key = fs.readFileSync(path.join(__dirname, '/ssl/server.key'), 'utf8'),
    cert = fs.readFileSync(path.join(__dirname, '/ssl/server.pem'), 'utf8');
// 创建证书对象
let cas = { key, cert };

// 引入请求体中间处理
const bodyParser = require('body-parser');
const $common = require('./common/common-req.js')
// 日志配置
logjs.configPath = path.join(__dirname, "/config/json/logConfig.json")
// 创建服务器
yun.use(logjs.actionLog())
// create application/json parser， 处理json格式
yun.use(bodyParser.json());
// create application/x-www-form-urlencoded parser，处理普通body格式
yun.use(bodyParser.urlencoded({ extended: false }));
// 监听静态资源
const staticPath = path.resolve('', path.join(__dirname, ''), '../public');
yun.use(`/${$common.projectName}/public`, express.static(staticPath));
console.log(staticPath)
// yun.use('/yun/public', express.static('public'));
let yunHttp = http.createServer(yun);
let yunHttps = https.createServer(cas, yun);
const eventServer = http.createServer((req, res) => {
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Access-Control-Allow-Origin': "*",
        'Access-Control-Allow-Headers': 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
    });
    setInterval(() => {
        res.write('data: The server time is: ' + new Date() + '\n\n event: message1\n');
            res.write(`id: 1\n`);
          res.write(`data: This is event 1\n`);
          res.write(`event: message\n\n`);
        
          res.write(`id: 2\n`);
          res.write(`event: message\n`);
          res.write(`data: This is event 2\n\n`);
    }, 1000);
    req.connection.addListener('close', () => {
        console.log('SSE connection closed!');
    }, false);
}).listen(4001);
initSocket(yunHttp)
// 跨域设置
yun.all("*", function(req, res, next) {
    console.log(req.method)
    // 请求拦截处理
	res.header('Access-Control-Allow-Origin', "*");
	res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length,Authorization,Accept,X-Requested-With');
	res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
	// res.header('X-Powered-By', '3.2.1')
    console.log('res聊到', req.method)
	if (req.method == 'OPTIONS') {
        res.sendStatus(200);
    }
	// /让options请求快速返回/
	else {
        let token = req.query.token ? req.query.token : req.body.token;
        let userId = req.query.userId ? req.query.userId : req.body.userId;
        console.log(req.originalUrl)
        console.log('Jinlai l22')
        next();
    }
});
// 路由中转
// 用户接口
yun.use(`/${$common.projectName}/user`, routerReq.userInfoReq)
yun.use(`/${$common.projectName}/upload`, routerReq.uploadReq)
// 文章接口
yun.use(`/${$common.projectName}/article`, routerReq.articleReq)
// 文章类型接口
yun.use(`/${$common.projectName}/category`, routerReq.categoryReq)
// 文章收藏接口
yun.use(`/${$common.projectName}/collect/article`, routerReq.articleCollectReq)
// 获取文章左侧
yun.use(`/${$common.projectName}/articleLeft`, routerReq.articleLeftListReq)
// 文章评论接口
yun.use(`/${$common.projectName}/comment`, routerReq.articleCommentReq)
// 留言
yun.use(`/${$common.projectName}/leaving`, routerReq.leavingReq)
// demo
yun.use(`/${$common.projectName}/demo`, routerReq.demoReq)
// demo收藏接口
yun.use(`/${$common.projectName}/collect/demo`, routerReq.demoCollectReq)
// 权限
yun.use(`/${$common.projectName}/manage/right`, routerReq.manageRight)
// 角色
yun.use(`/${$common.projectName}/manage/role`, routerReq.manageRole)
// 角色权限授予
yun.use(`/${$common.projectName}/manage/rightToRole`, routerReq.RightToRole)
// 用户角色授予
yun.use(`/${$common.projectName}/manage/roleToUser`, routerReq.roleToUser)
// 系统菜单
yun.use(`/${$common.projectName}/manage/sysmenu`, routerReq.sysMenu)
// 轮播图
yun.use(`/${$common.projectName}/common/carousel`, routerReq.carouselReq)
// 基础组件
yun.use(`/${$common.projectName}/component/basic`, routerReq.basicComponent)
// 基础组件属性
yun.use(`/${$common.projectName}/component/basic/attribute`, routerReq.basicComponentAttr)

// 监听服务端口
yunHttp.listen($common.port, $common.hostname, function() {
	console.log(`服务器启动成功！-- http://${$common.hostname}:${$common.port}/${$common.projectName}`)
})
yunHttps.listen($common.ports, $common.hostname, function() {
	console.log(`服务器启动成功！-- https://${$common.hostname}:${$common.ports}/${$common.projectName}`)
})



